import asyncio, math, random
from app.services.broker import dry_run
from app.models.order import Order

async def twap_worker(order_id: int):
    order = dry_run.get(order_id)
    slice_qty = math.ceil(order.qty / 6)
    for i in range(6):
        price = round(order.price * (1 + random.uniform(-0.002, 0.002)), 2)
        dry_run.execute(
            code=order.code,
            side=order.side,
            price=price,
            qty=min(slice_qty, order.qty - i*slice_qty)
        )
        await asyncio.sleep(10)   # 10 s 一发
    dry_run.status(order_id, 'filled')
